<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Role;
use think\Db;
use app\admin\model\User as UserModel;
use app\common\model\Department;

/**
 * 系统接口
 */
class Setting_0805 extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    /**
     * 首页
     *
     */
    public function getRoleList()
    {
        $where=[];
        $role = new \app\common\model\Role();
        $list = $role
            ->where($where)
            ->where('is_delete',0)
            ->order('id', 'desc')
            ->select();
        $this->success('请求成功', ['list' => $list]);
    }

    public function getRoleMenuIds()
    {
        $roleId = $this->request->post('roleId/d', 0);
        if (!$roleId) {
            $this->error('缺少角色ID');
        }

        $menuIds = Db::name('role_menu')
            ->where('role_id', $roleId)
            ->column('menu_id');

        $this->success('请求成功', ['menuIds' => $menuIds]);
    }

    public function saveRoleMenuIds()
    {
        $roleId = $this->request->post('roleId/d', 0);
        $menuIds = $this->request->post('menuIds/a', []);
        if (!$roleId) {
            $this->error('缺少角色ID');
        }

        Db::name('role_menu')->where('role_id', $roleId)->delete();

        $insertData = [];
        foreach ($menuIds as $menuId) {
            $insertData[] = [
                'role_id' => $roleId,
                'menu_id' => $menuId
            ];
        }
        if ($insertData) {
            Db::name('role_menu')->insertAll($insertData);
        }
        $this->success('保存成功');
    }
    public function getStaffList()
    {
        // 获取分页参数
        $page = $this->request->post('page', 1);
        $pageSize = $this->request->post('pageSize', 10);
        $roleId = $this->request->post('roleId', '');
        $department_id = $this->request->post('department_id', '');
        $name = $this->request->post('name', '');

        // 查询条件
        $where = [];
        
        // 处理部门ID，获取所有子部门ID
        if ($department_id) {
            // 获取所有子部门ID
            $departmentIds = $this->getChildDepartmentIds($department_id);
            // 将当前部门ID也加入数组
            $departmentIds[] = $department_id;
            $where['u.department_id'] = ['in', $departmentIds];
        }
        
        if ($roleId) {
            $where['u.role_id'] = $roleId;
        }
        if ($name) {
            $where['u.name'] = ['like','%'.$name.'%'];
        }


        $user = new \app\common\model\User();
        $total = $user->alias('u')->where($where)->where('u.is_delete',0)->count();
        $list = $user
            ->alias('u')
            ->join('fa_role r', 'u.role_id = r.id', 'left')
            ->join('fa_department d', 'u.department_id = d.id', 'left')
            ->field('u.*, r.name as role_name, d.title as department_name')
            ->where('u.is_delete',0)
            ->where($where)
            ->order('u.id', 'desc')
            ->page($page, $pageSize)
            ->select();

        $this->success('请求成功', ['list' => $list, 'total' => $total]);
    }

    /**
     * 递归获取所有子部门ID
     * @param int $parentId 父部门ID
     * @return array 子部门ID数组
     */
    private function getChildDepartmentIds($parentId)
    {
        $ids = [];
        $departments = Department::where('parent_id', $parentId)
            ->where('status', 1)
            ->where('is_delete', 0)
            ->select();
            
        foreach ($departments as $department) {
            $ids[] = $department['id'];
            // 递归获取子部门的子部门
            $childIds = $this->getChildDepartmentIds($department['id']);
            $ids = array_merge($ids, $childIds);
        }
        
        return $ids;
    }

    public function allMenuTree()
    {
        // 1. 查询所有菜单
        $menus = Db::name('menu')
            ->order('sort asc, id asc')
            ->select();

        // 2. 递归组装树
        $tree = $this->buildTree($menus);

        $this->success('请求成功', ['tree' => $tree]);
    }

    private function buildTree($menus, $parentId = 0)
    {
        $tree = [];
        foreach ($menus as $menu) {
            if ($menu['parent_id'] == $parentId) {
                $children = $this->buildTree($menus, $menu['id']);
                $tree[] = [
                    'key' => $menu['id'], // 用id，和checkedKeys类型一致
                    'title' => $menu['title'],
                    'children' => $children
                ];
            }
        }
        return $tree;
    }


    public function departmentList()
    {
        $list = Department::where('status', 1)->where('is_delete',0)->order('weigh desc,id asc')->select();
        $tree = $this->buildTree($list);
        $this->success('请求成功', ['tree' => $tree]);

    }
    public function UsersListByDept()
    {
        $list = User::where('status', 1)->order('weigh desc,id asc')->select();
        $tree = $this->buildTree($list);
        $this->success('请求成功', ['tree' => $tree]);

    }
    /**
     * 添加部门
     */
    public function createDepartment()
    {
        $title = $this->request->post('title');
        $parentId = $this->request->post('parentId/d', 0); // 默认为0，表示根部门

        if (empty($title)) {
            $this->error('部门名称不能为空');
        }

            $data = [
                'parent_id' => $parentId,
                'title' => $title,
                'createtime' => time(),
                'updatetime' => time(),
            ];
            // 使用 Department 模型创建
            $department = Department::create($data);

            if ($department) {
                $this->success('添加成功');
            } else {
                $this->error('添加失败');
            }

    }


    public function createRole()
    {
        $name = $this->request->post('name');

        if (empty($name)) {
            $this->error('名称不能为空');
        }

        $find= Role::where('is_delete',0)->where('name',$name)->find();
        if($find){
            $this->error('名称已存在');
        }

        $data = [
            'name' => $name,
        ];
        // 使用 Department 模型创建
        $role = Role::create($data);

        if ($role) {
            $this->success('添加成功');
        } else {
            $this->error('添加失败');
        }

    }
    public function editDepartment()
    {
        $id = $this->request->post('id/d');
        $name = $this->request->post('name');

        if (empty($id)) {
            $this->error('缺少部门ID');
        }
        if (empty($name)) {
            $this->error('部门名称不能为空');
        }

        // 使用 Department 模型查找
        $department = Department::get($id);
        if (!$department) {
            $this->error('部门不存在');
        }


            $data = [
                'title' => $name,
                'updatetime' => time(),
            ];
            // 使用 Department 模型更新
            $result = $department->save($data);

            if ($result !== false) { // save返回影响的行数，0也表示成功（数据未变），false表示失败
                $this->success('修改成功');
            } else {
                $this->error('修改失败');
            }

    }


    /**
     * 删除部门
     */
    public function delDepartment()
    {
        $id = $this->request->post('id/d');

        if (empty($id)) {
            $this->error('缺少部门ID');
        }

        // 使用 Department 模型查找
        $department = Department::get($id);
        if (!$department) {
            $this->error('部门不存在');
        }

        // 检查是否有子部门，如果有，则不允许删除
        $hasChildren = Department::where('parent_id', $id)->where('is_delete',0)->count();
        if ($hasChildren > 0) {
            $this->error('该部门下存在子部门，请先删除子部门');
        }

        // 检查部门下是否有员工
        $hasStaff = UserModel::where('department_id', $id)->where('is_delete',0)->count(); // 使用 UserModel 检查
        if ($hasStaff > 0) {
            $this->error('该部门下存在员工，请先移除或转移员工');
        }

            // 使用 Department 模型删除
            $department->is_delete = 1;

            // 保存更改
            $result = $department->save();

            if ($result !== false) {

                $this->success('删除成功');
            } else {

                $this->error('删除失败');
            }

    }

    public function getStaffDetail()
    {
        $id = $this->request->post('id/d');

        if (empty($id)) {
            $this->error('缺少员工ID');
        }

        $user = UserModel::get($id);

        if (!$user) {
            $this->error('员工不存在');
        }

        $detail = $user->toArray(); // 转换为数组，方便添加新字段

        // 获取直属上级的姓名
        if (!empty($detail['leader_id'])) {
            $leader = UserModel::get($detail['leader_id']);
            if ($leader) {
                $detail['leader_name'] = $leader['name'];
            } else {
                $detail['leader_name'] = '';
            }
        } else {
            $detail['leader_name'] = '';
        }

        // 获取部门的完整路径
        if (!empty($detail['department_id'])) {
            $detail['department_path'] = $this->getDepartmentPath($detail['department_id']);
        } else {
            $detail['department_path'] = [];
        }

        $this->success('请求成功', ['detail' => $detail]);
    }
    /**
     * 获取部门完整路径（从根到当前部门）
     */
    private function getDepartmentPath($departmentId, $path = [])
    {
        if (empty($departmentId)) {
            return $path;
        }

        $department = Department::get($departmentId);
        if (!$department) {
            return $path;
        }

        // 将当前部门ID添加到路径最前端
        array_unshift($path, $department['id']);

        // 递归查找父部门
        if ($department['parent_id'] !== 0) {
            return $this->getDepartmentPath($department['parent_id'], $path);
        } else {
            return $path;
        }
    }



    public function delStaff()
    {
        $id = $this->request->post('id/d');
        
        if (empty($id)) {
            $this->error('缺少员工ID');
        }

        // 查找员工
        $user = UserModel::get($id);
        if (!$user) {
            $this->error('员工不存在');
        }

 
        // 修改手机号（在末尾加0）
        $mobile = $user->mobile;
        if (!empty($mobile)) {
            $user->mobile = $mobile . '0';
        }
        
        // 设置软删除标记
        $user->is_delete = 1;
        
        // 保存更改
        $result = $user->save();
        
        if ($result !== false) {
        
            $this->success('删除成功');
        } else {
           
            $this->error('删除失败');
        }
       
    }
    public function saveRoleDataPermission()
    {
        $id = $this->request->post('roleId');
        $dataPermissionType = $this->request->post('dataPermissionType');

        if (empty($id)) {
            $this->error('缺少ID');
        }

        // 查找员工
        $role = Role::get($id);
        if (!$role) {
            $this->error('角色不存在');
        }
        // 设置软删除标记
        $role->dataPermissionType = $dataPermissionType;
        // 保存更改
        $result = $role->save();
        if ($result !== false) {

            $this->success('修改成功');
        } else {

            $this->error('修改失败');
        }

    }

    public function getRoleDataPermission()
    {
        $id = $this->request->post('roleId');

        if (empty($id)) {
            $this->error('缺少ID');
        }

        // 查找员工
        $role = Role::get($id);
        if (!$role) {
            $this->error('角色不存在');
        }
        // 设置软删除标记

        // 保存更改


         $this->success('ok',['dataPermissionType'=> $role->dataPermissionType]);


    }

    public function delRole()
    {
        $id = $this->request->post('id/d');

        if (empty($id)) {
            $this->error('缺少员工ID');
        }
        // 查找员工
        $role =Role::get($id);
        if (!$role) {
            $this->error('角色不存在');
        }

        // 设置软删除标记
        $role->is_delete = 1;

        // 保存更改
        $result = $role->save();

        if ($result !== false) {

            $this->success('删除成功');
        } else {

            $this->error('删除失败');
        }

    }


    public function editStaff()
    {
        $id = $this->request->post('id');
        $name = $this->request->post('name');
        $gender = $this->request->post('gender');
        $department_id = $this->request->post('department_id');
        $leaderId = $this->request->post('leaderId');
        $mobile = $this->request->post('mobile');
        $roleId = $this->request->post('roleId');
        $email = $this->request->post('email');
        $newpassword=$this->request->post('password');
        $status=$this->request->post('status');

        if (!$id || !$name || !$mobile) {
            $this->error(__('Invalid parameters'));
        }

        // 检查手机号是否已被其他用户使用
        $exists = \app\common\model\User::where('mobile', $mobile)
            ->where('id', '<>', $id)
            ->where('is_delete', 0)
            ->find();
        if ($exists) {
            $this->error(__('手机号已经存在'));
        }

        // 检查姓名是否已被其他用户使用
        $exists = \app\common\model\User::where('name', $name)
            ->where('id', '<>', $id)
            ->where('is_delete', 0)
            ->find();
        if ($exists) {
            $this->error(__('姓名已经存在'));
        }

        $user=UserModel::get($id);
        $param=[
            'name' => $name,
            'gender' => $gender,
            'department_id' => $department_id,
            'leader_id' => $leaderId,
            'mobile' => $mobile,
            'role_id' => $roleId,
            'email' => $email,
            'gender'=> $gender,
            'status'=> $status
        ];
        if(!empty($newpassword)){
            $newpassword= $this->auth->getEncryptPassword($newpassword, $user->salt);
            $param['password'] = $newpassword;
        }

        $user->save($param);

        $this->success(__('更新成功'));

    }


}
